#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstdio>
using namespace std;
void Usage(string proc)
{
  cout<<"Usage: \n\t"<<proc<<"server_ip server_port"<<endl; 

}
int main(int argc,char* argv[])
{
  if(argc!=3)
  {
   Usage(argv[0]);
   return 0;
  }
   


  //创建套接字
  int sock = socket(AF_INET,SOCK_DGRAM,0); 
  if(sock<0)
  {
    cout<<"sock fail!"<<endl;
    return 1;
  }

  //客户端需要bind? 不需要
  
  //2.使用服务   

   struct sockaddr_in server;
   server.sin_family = AF_INET; 
   server.sin_port =htons(atoi(argv[2]));
   server.sin_addr.s_addr = inet_addr(argv[1]);
  while(1)
  {
   string message;
   cout<<"输入:  ";
  // cin>>message;
     getline(cin,message);
   sendto(sock, message.c_str(), message.size(),0,(struct sockaddr*)&server,sizeof(server));
   
   struct sockaddr_in tmp;
   socklen_t len = sizeof(tmp);
   char buffer[1024];

   ssize_t cnt = recvfrom(sock, buffer,sizeof(buffer),0,(struct sockaddr*)&tmp,&len);
   if(cnt>0)
   {
     buffer[cnt]='\0';
     cout <<"server echo# "<<buffer<<endl;
   }
  }

  return 0;
} 
